﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using Domain.Model.Partners;

namespace Domain.Model.Orders
{
    public class Order
    {
        public Order()
        {
            OrderLines = new HashSet<OrderLine>();
            Payments = new HashSet<Payment>();
        }
   
        public System.Guid ID { get; set; }
        public int Number { get; set; }
        public decimal TotalSum { get; set; }
        public OrderType Type {get;set;}
        public OrderState State { get; set; }
        public string PaymentStatus { get; set; }
        public bool IsClosed { get; set; }
        public string Description { get; set; }

        public DateTime CreatedOn { get; set; }
        public Nullable<System.DateTime> UpdatedOn { get; set; }
    
        public virtual ICollection<OrderLine> OrderLines { get; set; }
        public virtual ICollection<Payment> Payments { get; set; }
        
        #region Public methods

        public decimal GetOrderSum()
        {
            decimal sum = 0;

            foreach (var orderLine in OrderLines)
            {
                sum += orderLine.Price.Value*orderLine.Quantity;
            }

            return sum;
        }

        public double PaymentProgress()
        {
            decimal paymentProgress = 0;
            decimal orderTotalSum = GetOrderSum();
            decimal totalPayments = GetTotalPaymentsSum();

            paymentProgress = (totalPayments/orderTotalSum);
            return (double)Math.Round(paymentProgress, 2, MidpointRounding.ToEven);
        }
        
        public bool IsPaid()
        {
            return PaymentProgress() == 1;
        }

        public string NumberToString()
        {
            int dimention = 8;
            string additionChars = string.Empty;

            var number = Number.ToString();
            int additionDimention = dimention - number.Length;

            for (int i = 0; i < additionDimention; i++)
            {
                additionChars += "0";
            }

            number = string.Format("{0}{1}", additionChars, number);

            return number;
        }

        public decimal GetTotalPaymentsSum()
        {
            decimal totalPaymentsSum = 0;

            foreach (var payment in Payments)
            {
                totalPaymentsSum += payment.Sum;
            }

            return totalPaymentsSum;

        }

        #endregion // Public methods

    }
}
